package github.redspider;

import cn.hutool.core.lang.UUID;

import java.util.concurrent.*;

/**
 * @Auther DRevelation
 * @Date 2019-09-02 15:48
 * @Desc
 */
class BlockingQueueDemo {

    private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 1; i++) {
            service.submit(new Producer(queue));
        }

        for (int i = 0; i < 2; i++) {
            service.submit(new Consumer(queue));
        }
    }

    static class Producer implements Runnable {

        private BlockingQueue queue;

        public Producer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    String uuid = UUID.fastUUID().toString();
                    System.out.println("生产者" + Thread.currentThread().getName() + " 生产数据 " + uuid);
                    queue.put(uuid);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer implements Runnable {

        private BlockingQueue queue;

        public Consumer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    String element = (String) queue.take();
                    System.out.println("消费者" + Thread.currentThread().getName() + "  消费数据 " + element);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


